import { HttpClient } from "@angular/common/http";
import { ChangeDetectorRef, Component, Input, OnInit, Output, EventEmitter } from "@angular/core";
import { Router } from "@angular/router";
import { DValidateRules, FormLayout, ToastService } from "ng-devui";
import { delay, of } from "rxjs";
import { UserAuthService } from "src/app/@core/user-auth.service";
import { AuthGuardService } from '../../@core/auth-guard-service.guard';
import { Store } from '@ngrx/store'
import { AppState } from 'src/app/store'
import { CookieService } from 'ngx-cookie-service'

@Component({
  selector: "app-register",
  templateUrl: "./register.component.html",
  styleUrls: ["./register.component.scss"],
})
export class RegisterComponent implements OnInit {
  @Output() fun: EventEmitter<any> = new EventEmitter<any>();
  layoutDirection: FormLayout = FormLayout.Vertical;
  msgs: Array<Object> = [];

  existUsernames = ["dyp"];
  showPassword = false;
  isShared = false;
  options = ["+86"];

  formData = {
    userName: "",
    password: "",
    authentiCode: "",
    telephoneNumber: "",
    verificationCode: "",
  }

  formRules: { [key: string]: DValidateRules } = {
    rule: {
      messageShowType: "text",
      message: "校验失败，请检查注册信息",
    },
    usernameRules: {
      validators: [
        { required: true, message: "用户名不能为空" },
        { minlength: 3 },
        { maxlength: 32 },
        {
          pattern: /^(?![0-9]+$)[0-9A-Za-z]{3,32}$/,
          message: {
            "zh-cn": "仅允许输入数字与大小写字母, 且必须包含字母",
            "en-us":
              "The user name cannot contain characters except uppercase and lowercase letters.",
          },
        },
      ],
      asyncValidators: [
        {
          sameName: this.checkName.bind(this),
          message: {
            "zh-cn": "用户名重名",
            "en-us": "Duplicate name.",
          },
        },
      ],
    },

    passwordRules: {
      validators: [
        { required: true, message: "密码不能为空" },
        { minlength: 8 },
        { maxlength: 32 },
        {
          pattern:
            /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[~!@#$%^&*()_+{}|":<>?`[\];',.\/])[\da-zA-Z~!@#$%^&*()_+{}|":<>?`[\];',.\/]{8,32}$/,
        },
      ],
      message: "密码至少包含大小写字母、数字和特殊字符(~!@#$%^&*()_+{})",
    },

    authentiCodeRules: {
      validators: [{ required: true, message: "验证码不能为空" }],
      message: "请输入包含4位数字或字母的验证码",
    },

    phoneNumRules: {
      validators: [
        { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: "请输入规范的手机号" },
      ],
    },

    codeRules: {
    },
  }

  codeImg: string;

  constructor(
    private userAuthService: UserAuthService,
    private store: Store<AppState>,
    private router: Router,
    private http: HttpClient,
    private toastService: ToastService,
    private authGuardService: AuthGuardService,
    private cdr: ChangeDetectorRef,
    private cookieService: CookieService
  ) { }

  ngOnInit(): void {
    this.reFreshCodeImg();
    this.starttime = parseInt(localStorage.getItem("getTelCodeTimeReg"))
    this.countDown = this.starttime > new Date().getTime()
  }

  reFreshCodeImg() {
    this.userAuthService.getCaptcha().subscribe((res) => {
      this.codeImg = "data:image/jpg;base64," + res.data;
    })
  }

  activeTabChange(tab) { }

  maxUsers(num) {
    return (val) => {
      return !val || val.length <= num;
    }
  }

  submitForm({ valid, directive }) {
    if (valid) {
      this.userAuthService
        .userExistTest(this.formData.userName)
        .subscribe((response) => {
          if (response.code == 0) {
            this.userAuthService
              .userRegister(
                this.formData.userName,
                this.formData.password,
                this.formData.authentiCode,
                this.formData.telephoneNumber,
                this.formData.verificationCode
              )
              .subscribe((res) => {
                this.submitSuccess(res);
              });
          } else {
            this.toastService.open({
              value: [
                { severity: "error", summary: "Error", content: response.msg },
              ],
            });
          }
        });
    } else {
      this.showToast("error", "Error", "请检查表单！");
    }
  }

  submitSuccess(res) {
    if (res.code === 0) {
      localStorage.removeItem("getTelCodeTimeReg")
      this.router.navigate(["/register/success/"], { queryParams: { userName: this.formData.userName, telNum: this.formData.telephoneNumber } });
      localStorage.setItem('userId', res.data.userId)
      localStorage.setItem('userName', res.data.userName)
      localStorage.setItem('ROLE', res.data.role)
      localStorage.setItem('PasswordChange', res.data.pwdChanged)
      this.userAuthService.getCurrentUser(res.data)
      this.getAvatar(res.data.userId)
      this.judgeDisabled()
      this.addMenu(res)
    } else {
      this.toastService.open({
        value: [{ severity: "error", summary: "Error", content: res.msg }],
      })
    }
  }

  getAvatar(userId) {
    this.userAuthService.getAvatar(userId).subscribe((res) => {
      this.store.dispatch({
        type: 'AVATAR',
        payload: res.data.FileUrl
      })
    })
  }

  judgeDisabled() {
    this.authGuardService.getBlockChainType().subscribe((res) => {
      if (res.data.type === 'shared') {
        this.isShared = true
        this.cdr.markForCheck()
      } else {
        this.isShared = false
        localStorage.setItem('IS_SHARED', '1')
        this.store.dispatch({
          type: 'ADD_TODO',
          payload: {
            name: '区块链',
            value: '2',
            link: '/blockchain',
            img: '../../../assets/img/home/blockchain.svg'
          }
        })
        this.cdr.markForCheck()
      }
    })
  }

  addMenu(res) {
    if (res.data.role === 'admin') {
      this.store.dispatch({
        type: 'ADD_TODO',
        payload: {
          name: '管理',
          value: '4',
          link: '/manage/collection',
          img: '../../../assets/img/home/setting.svg'
        }
      })
    }
  }

  checkName(value) {
    let res = true;
    if (this.existUsernames.indexOf(value) !== -1) {
      res = false;
    }
    return of(res).pipe(delay(500));
  }

  showToast(type: any, title: string, msg: string) {
    this.msgs = [{ severity: type, summary: title, detail: msg }];
  }

  countDown = false;
  starttime: any;

  callGetList() {
    this.countDown = false;
  }

  getCode() {
    this.userAuthService.getPhoneCaptcha(this.formData.telephoneNumber, true).subscribe((res) => {
      if (res.code != 0) {
        this.authGuardService.showModalPanel('warning', res.msg)
      }
      else {
        localStorage.setItem("getTelCodeTimeReg", res.data.cooldownTime)
        if (res.data.cooldownTime > new Date().getTime()) {
          this.countDown = true;
          this.starttime = parseInt(localStorage.getItem("getTelCodeTimeReg"))
        }
        else {
          this.countDown = false;
        }
      }
    })
  }
}
